<template>
  <div class="i_bg">
    <div class="postion">
      <el-empty v-if="product == null" description="商品不存在"></el-empty>
      <span class="fl" v-if="product != null">
        <router-link :to="{ name: 'GoodsList', query: { searchTxt: '' } }"
          >全部</router-link
        >
        <template v-if="levelName1 != null">
          >
          <router-link
            :to="{
              name: 'GoodsList',
              params: { type: 1, categoryId: product.categoryLevel1Id },
            }"
            >{{ levelName1 }}</router-link
          >
        </template>
        <template v-if="levelName2 != null">
          >
          <router-link
            :to="{
              name: 'GoodsList',
              params: { type: 2, categoryId: product.categoryLevel2Id },
            }"
            >{{ levelName2 }}</router-link
          >
        </template>
        <template v-if="levelName3 != null">
          >
          <router-link
            :to="{
              name: 'GoodsList',
              params: { type: 3, categoryId: product.categoryLevel3Id },
            }"
            >{{ levelName3 }}</router-link
          >
        </template>
      </span>
    </div>
    <div class="content" v-if="product != null">
      <div id="tsShopContainer">
        <div id="tsImgS" v-if="product != null">
          <img :src="imagesDir + product.fileName" width="390" height="390" />
        </div>
      </div>

      <div class="pro_des">
        <div class="des_name">
          <p>{{ product.name }}</p>
          {{ product.description }}
        </div>
        <div class="des_price">
          本店价格：<b>{{ product.price }}</b
          ><br />
        </div>
        <div class="des_share">
          <div class="d_care">
            <a @click="addToFavorite(product.id)">收藏商品</a>
          </div>
        </div>
        <div class="des_join">
          <div class="j_nums">
            <input type="text" v-model.number="number" class="n_ipt" @blur="validData()"/>
            <input
              type="button"
              @click="number++" 
              class="n_btn_1"
            />
            <input type="button" 
              @click="number > 1 ? number-- : 1"
              class="n_btn_2" />
          </div>
          <span class="fl"
            ><a @click.prevent="addInCar(product)"
              ><img src="@/assets/images/j_car.png" /></a
          ></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Empty } from "element-ui";
Vue.use(Empty);
// import { mapState } from 'vuex';
export default {
  data() {
    return {
      order: null,
      number: 1,
      loginName: '',
      product: null,
      userId: null,
      imagesDir: sessionStorage.getItem("imagesDir"),
      levelName1: null,
      levelName2: null,
      levelName3: null,
      firstLevelList: JSON.parse(sessionStorage.getItem("firstLevelList")),
      levelMap: JSON.parse(sessionStorage.getItem("levelMap")),
    };
  },
  watch: {
    $props: {
      immediate: true,
      deep: true,
      handler(props) {
        this.getProductById(props.id);
      },
    },
    order: {
      deep: true,
      handler(newOrder) {
        this.$store.commit("setOrder", newOrder);
      },
    },
  },
  methods: {
    getProductById(id) {
      this.$axios({
        url: "/api/product/detail",
        method: "POST",
        data: {
          id: id,
        },
      }).then((rs) => {
        this.product = rs.data.product;
        if (this.product) {
          //初始化levelName
          this.getLevelName();
        }
      });
    },
    getLevelName() {
      console.log("firstLevelList", this.firstLevelList);
      console.log("levelMap", this.levelMap);
      this.firstLevelList.forEach((i) => {
        if (i.id == this.product.categoryLevel1Id) {
          this.levelName1 = i.name;
        }
      });
      if (this.product.categoryLevel2Id != 0) {
        this.levelMap[this.levelName1].forEach((i) => {
          if (i.id == this.product.categoryLevel2Id) this.levelName2 = i.name;
        });
      }
      if (this.product.categoryLevel3Id != 0) {
        this.levelMap[this.levelName2].forEach((i) => {
          if (i.id == this.product.categoryLevel3Id) this.levelName3 = i.name;
        });
      }
    },
    addInCar(product) {
      //将商品加入购物车，每次点击只会        ----- 用户必须登录才能加入购物车 -----
      if(!sessionStorage.getItem("loginName")) {
        this.$message.warning("请先登录！");
        this.$router.push({name: 'Login'});    
        return;
      }
      //根据product的id实时查询商品的数量，防止多用户下数量不一致
      this.$axios({
        url: "/api/product/detail",
        method: "POST",
        data: {
          id: product.id,
        },
      }).then((rs) => {
        console.log("实时查询商品数量", rs.data.product);
        product = rs.data.product;
        if (product.stock >= this.number) {
          this.subProductStock(product, this.number);
          this.addProductNumberInCar(product, this.number);
            this.$message.success("加入购物车成功！")

        }else {
            this.$message.warning("商品库存不够")
        }
      });
    },
    subProductStock(product, number) {
      //执行商品库存减少操作, 减少的数量为number
      //修改后再修改es中上平的数量
      product.stock -= parseInt(number);
      this.$axios({
        url: "/api/product/update0",
        method: "POST",
        data: product,
      }).then((rs) => {
        console.log("修改es单个商品结果", rs.data.msg);
      });
    },
    addProductNumberInCar(product, number) {
      //执行购物车中商品的增加操作，增加的数量为number
      this.order = this.$store.state.order;
      //先修改页面中的数据及
      let pExist = false; //判断购物车是否有该商品
      if (this.order) {
        if (!this.order.orderDetailList) this.order.orderDetailList = [];
        for (let i = 0; i < this.order.orderDetailList.length; i++) {
          if (this.order.orderDetailList[i].productId == product.id) {
            pExist = true;
            this.order.orderDetailList[i].quantity += parseInt(number);
            this.order.cost += number * product.price;
            this.order.orderDetailList[i].name = product.name;
            this.order.orderDetailList[i].fileName = product.fileName;
          }
        }
      }
      //购物车中不存在该商品
      if (!pExist) {
        this.order.orderDetailList.push({
          productId: product.id,
          quantity: number,
          cost: product.price,
          name: product.name,
          fileName: product.fileName,
        });
        if (this.order.cost) {
          this.order.cost += product.price * number;
        } else {
          this.order.cost = product.price * number;
        }
      }

      //修改后订单存到redis中去
      this.$axios({
        url: "/api/order/modify",
        method: "POST",
        data: this.order,
      }).then((rs) => {
        console.log("redis中购物车订单修改结果", rs.data.msg);
      });
    },
    addToFavorite(productId) {
      if(!sessionStorage.getItem("loginName")) {
        this.$message.warning("请先登录！");
        this.$router.push({name: 'Login'});    
        return;
      }
      this.$axios({
        url: "/api/collection/add",
        method: "POST",
        data: {
          userId: this.userId,
          productId: productId,
        },
      })
        .then((res) => {
          if (res.data.code === 5200) {
            this.$message.success("收藏成功");
          } else {
            this.$message.error(res.data.msg || "收藏失败");
          }
        })
        .catch((err) => {
          this.$message.error("网络异常，请稍后再试");
          console.error(err);
        });
    },
    getUserId() {
      this.$http
        .post(
          "/api/address/getUserId",
          "token=" + sessionStorage.getItem("token")
        )
        .then((res) => {
          this.userId = res.data.userId;
        });
    },
    validData() {
      if(this.number <= 0) {
        this.$message.error("输入的商品数量不能小于0");
        this.number = 1;
      } 
      this.number = Math.abs(this.number)
    }
  },
  props: ["id"],
  created() {
    this.loginName = sessionStorage.getItem("loginName") 
    if(this.loginName) {
      this.getUserId();
    }  
    this.order = this.$store.state.order;
    //初始化
    if(this.order) {
      this.order.orderDetailList.forEach((i) => {
        this.quantityListLast[i.productId] = i.quantity;
        this.$set(this.quantityListNow, i.productId, i.quantity);
      });
    }
    
  },
};
</script>

<style scoped > 

</style>
